import datetime
import webapp2
import models
import gviz_api

class CurrencyCompareHandler(webapp2.RequestHandler):
    def get(self):
        date_from = self.request.get('from')
        date_to = self.request.get('to')
        tqx = self.request.get('tqx')
        
        try:
            date_from = datetime.date(int(date_from[0:4]), int(date_from[4:6]), int(date_from[6:8]))
            date_to = datetime.date(int(date_to[0:4]), int(date_to[4:6]), int(date_to[6:8]))
        except:
            raise Exception("bad date parameters")
            #TODO: handle properly
            
        rates = models.ExchangeRate.compare(date_from, date_to)
        description = {
                       "country": ("string", "Country"),
                       "change": ("number", "Change"),
                       "detail": ("string", "Detail")
                       }
        data = []
        for unit in sorted(rates.keys()):
            country = unit[:2]
            country_name = models.Country.get_name(country)
            if not country_name: continue
            units_per_usd_from, units_per_usd_to = rates[unit]
            change = units_per_usd_from / units_per_usd_to
            detail = "{0}: {1:03.3f} ({2:03.3f} to {3:03.3f})".format(unit, change, units_per_usd_from, units_per_usd_to)
            
            data.append({
                         "country":country,
                         "change":change,
                         "detail":detail
                         })
        data_table = gviz_api.DataTable(description)
        data_table.LoadData(data)
        
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(data_table.ToResponse(
                                                          ("country", "change", "detail"),
                                                          "country",
                                                          tqx=tqx))
        
currency_compare_handler = webapp2.WSGIApplication([('/data/currency_compare', CurrencyCompareHandler)], debug=True) 